package com.yl.auth.controller;

import com.alibaba.excel.util.CollectionUtils;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.yl.common.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.activiti.bpmn.converter.BpmnXMLConverter;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.editor.constants.ModelDataJsonConstants;
import org.activiti.editor.language.json.converter.BpmnJsonConverter;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Model;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;


/**
 * @author 王庆梁
 * @datetime 2023/7/19 16:56
 * @description 类对象
 */
@RestController
@RequestMapping("/admin/activiti-explorer/model")
@Api(tags = "基础设置-审批")
@CrossOrigin
public class ModelerController {

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private ObjectMapper objectMapper;

    /**
     *
     * @param name 流程姓名
     * @param key
     * @param description 流程详细
     * @return
     */
    @GetMapping(value = "/create/{name}/{key}/{description}")
    @ApiOperation(value = "创建新的模型")
    public Result create(@ApiParam(value = "模型名称")@PathVariable("name") String name, @PathVariable(value = "key",required = false) String key,
                         @ApiParam(value = "描述") @PathVariable(value = "description", required = false) String description) {
        String id = "";
        try {
            //初始化一个空模型
            Model model = repositoryService.newModel();
            //设置一些默认信息
            int revision = 1;
            ObjectNode modelNode = objectMapper.createObjectNode();
            modelNode.put(ModelDataJsonConstants.MODEL_NAME, name);
            modelNode.put(ModelDataJsonConstants.MODEL_DESCRIPTION, description);
            modelNode.put(ModelDataJsonConstants.MODEL_REVISION, revision);
            model.setName(name);
            model.setKey(key);
            model.setMetaInfo(modelNode.toString());
            repositoryService.saveModel(model);
            id = model.getId();
            //完善ModelEditorSource
            ObjectNode editorNode = objectMapper.createObjectNode();
            editorNode.put("id", "canvas");
            editorNode.put("resourceId", "canvas");
            ObjectNode stencilSetNode = objectMapper.createObjectNode();
            stencilSetNode.put("namespace", "http://b3mn.org/stencilset/bpmn2.0#");
            editorNode.putPOJO("stencilset", stencilSetNode);
            repositoryService.addModelEditorSource(id, editorNode.toString().getBytes("utf-8"));
            return Result.ok(id);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.ok("失败");
    }

    /**
     * 导出model的npmn.xml文件
     */
    @ApiOperation(value = "根据modelId导出文件")
    @GetMapping(value = "/export/{modelId}")
    public Result export(@PathVariable String modelId,HttpServletResponse response) {
        try{
            //返回{@link Model}
            Model model = repositoryService.getModel(modelId);
            BpmnJsonConverter jsonConverter = new BpmnJsonConverter();
            JsonNode jsonNode = new ObjectMapper().readTree(repositoryService.getModelEditorSource(model.getId()));
            BpmnModel bpmnModel = jsonConverter.convertToBpmnModel(jsonNode);
            //流程非空判断
            if(!CollectionUtils.isEmpty(bpmnModel.getProcesses())) {
                BpmnXMLConverter xmlConverter = new BpmnXMLConverter();
                byte[] bytes = xmlConverter.convertToXML(bpmnModel);
                //用于从内存中读取字节数据
                ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
                String fileName = bpmnModel.getMainProcess().getId()+ ".bpmn20.xml";
                System.out.println("名称:"+fileName);
                response.setHeader("Content-Disposition","attachment;filename="+fileName);
                IOUtils.copy(inputStream,response.getOutputStream());
                response.flushBuffer();
            }
            return Result.ok("导出成功");
        } catch (IOException e) {
            e.printStackTrace();
            return Result.ok("导出失败");
        }
    }
}
